open FrCore
open FrGui

let safe_int_of_string s =
	try int_of_string s
	with Failure _ -> 0

let repr_of_int = function
	| 0 -> lift "Zero"
	| 1 -> lift "One"
	| 2 -> lift "Two"
	| 3 -> lift "Three"
	| _ -> lift "???"

let _ =
	init ();
	
	let x_slider, x = vslider 0.5 in
	let x_label = dynamic_label (lift (string_of_float @x))
	and x_bar = progress_bar x in
	
	let on_off_widgets, on_off = radio_button_group ["Enabled", true; "Disabled", false] true in
	
	let clicky_button, clicky = button ~enabled: on_off ~label:"clicky" () in
	let clicky_ticker = progress_ticker clicky in
	
	let error_button, error = button ~label:"break" "You broke it!" in
	let error_popup, yesno = message_box ["Yes", "Y"; "No", "N"] error in
	
	let yesno_label = text_view ~width: 1 (hold yesno "") in
	
	let status_box, status = text_entry "" in
	let status_bar = status_bar status in
	
	let choices_box, choices_string = text_entry "1 2 3 4" in
	let @choices =
		List.map safe_int_of_string (Str.split (Str.regexp " +") @choices_string) in
	
	let choices_list, choice = list_box repr_of_int choices [] in
	let @sum = List.fold_left (+) 0 @choice in
	let sum_label = text_view ~width: 3 (lift (string_of_int @sum)) in
	
	let new_item, new_event = menu_action "New" ()
	and open_item, open_event = menu_action "Open..." ()
	and close_item, close_event = menu_action "Close" () in
	let main_menu =
		menu_bar ["File", menu [(lift [new_item; open_item]); (lift [close_item])]] in
	
	let file_popup, filename_event =
		alert (on open_event () -> "Open file!")
	and close_popup, close_event =
		message_box
			["Quit", Some (); "Not yet", None]
			(on close_event () -> "Are you sure you want to quit?") in
	
	let layout1 = hsplit (
		frame (hbox [
			x_slider;
			yesno_label;
			vbox (List.append on_off_widgets [empty; clicky_button; error_button])]),
		frame ~label: "The right" (hbox [
			vbox [x_label; x_bar; clicky_ticker; status_box];
			vbox [choices_box; choices_list];
			sum_label])
	) in
	
	let label_choice = label "testing!"
	and button_choice, _ = button ~label: "clicking!" () in
	let widget_radio_group, which_widget =
		radio_button_group [
				"Label", label_choice;
				"Button", button_choice ]
			label_choice in
	
	let layout2 = hbox [
		vbox widget_radio_group;
		collapse_w which_widget;
	] in
	
	let layout = tabbed [
		"Main", layout1;
		"collapse_w", layout2;
	] in
	
	let main_window = window
		~transients: [error_popup; file_popup; close_popup]
		~status_bar: status_bar
		~menu_bar: main_menu
		layout in
	
	ignore main_window;
	
	main ~exit: (may_e close_event) ()
